package org.ioriframework.plugin.maven.console;

import java.text.SimpleDateFormat;

import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.SubContributionItem;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleConstants;
import org.eclipse.ui.console.IConsoleManager;
import org.ioriframework.plugin.maven.Constants;
import org.ioriframework.plugin.maven.util.StringUtils;

/**
 * 控制台工厂类
 * @author iori
 *
 */
public class ConsoleFactory {

	/**
	 * 当前线程对应的控制台
	 */
	private static final ThreadLocal<Console> console = new ThreadLocal<Console>();
	
	/**
	 * 默认控制台管理器
	 */
	private static IConsoleManager manager = ConsolePlugin.getDefault().getConsoleManager();
	
	/**
	 * 新建console
	 * @return
	 */
	private static Console createConsole() {
		// 新建console实例
		Console newConsole = new Console(getConsoleDescription(), null);
		// 添加到控制台管理器中
		manager.addConsoles(new IConsole[] {newConsole});
		return newConsole;
	}
	
	/**
	 * 获取当前console实例
	 * @return
	 */
	public static Console currentConsole() {
		Console con = console.get();
		// 不存在则新建
		if (con == null) {
			con = createConsole();
			console.set(con);
		}
		// 激活console窗口
		con.activate();
		return con;
	}
	
	/**
	 * 清除当前console实例
	 */
	public static void removeCurrentConsole() {
		Console con = console.get();
		// 存在则清除
		if (con != null) {
			try {
				// 标识当前任务为停止状态
				con.setRunning(false);
				// 更新按钮状态
				Display.getDefault().syncExec(new Runnable() {
					
					@Override
					public void run() {
						refreshBtn(false);
					}
					
					/**
					 * 更新控制台按钮状态
					 * @param isRunning
					 */
					private void refreshBtn(boolean isRunning) {
						IWorkbenchPage page = PlatformUI.getWorkbench().getWorkbenchWindows()[0].getPages()[0];
						IViewPart viewPart = page.findView(IConsoleConstants.ID_CONSOLE_VIEW);
						IActionBars actionBar = viewPart.getViewSite().getActionBars();
						IToolBarManager toolbarMgr = actionBar.getToolBarManager();
						IContributionItem[] items = toolbarMgr.getItems();
						for (IContributionItem item : items) {
							if (item instanceof SubContributionItem) {
								IAction action = ((ActionContributionItem) ((SubContributionItem) item).getInnerItem()).getAction();
								String text = action.getText();
								// 找到按钮，更新状态
								switch (text) {
								case Constants.ACTION_TEXT_TERMINATE:
									action.setEnabled(isRunning);
									break;
								case Constants.ACTION_TEXT_REMOVEALL:
								case Constants.ACTION_TEXT_REMOVE:
									action.setEnabled(!isRunning);
									break;
								default:
									break;
								}
							}
						}
						actionBar.updateActionBars();
					}
				});
				// 更新控制台描述
				updateDescription();
			} finally {
				console.set(null);
			}
		}
	}
	
	/**
	 * 获取控制台描述
	 * @return
	 */
	public static String getConsoleDescription() {
		// 如果console为空，说明正在初始化
		if (console.get() == null) {
			return "<Initializing> [Maven Jetty]";
		}
		// 任务状态
		String status = console.get().isRunning() ? "Running" : (console.get().isForceTerminate() ? "Terminated" : "Stopped");
		// 运行的项目
		String projectName = console.get().getProjectName();
		// 运行的命令
		String command = console.get().getCommand();
		// 任务开始运行的时间
		String startTime = new SimpleDateFormat(Constants.DATE_FORMAT).format(console.get().getStartTime());
		return StringUtils.format("<{0}> {1} [Maven Jetty] {2} ({3})", new Object[] {status, projectName, command, startTime});
	}
	
	/**
	 * 更新控制台描述
	 */
	public static void updateDescription() {
		console.get().setDescription(getConsoleDescription());
	}
}
